#include "Util.hpp"
#include <cstdio>
#include <vector>
#include <functional>
using func_t = std::function<void()>;
#define INIT(v)                  \
    do                           \
    {                            \
        v.push_back(printlog);   \
        v.push_back(download);   \
        v.push_back(executeSql); \
    } while (0)
#define EXEC_OTHER(cbs)            \
    do                             \
    {                              \
        for (auto const &cb : cbs) \
            cb();                  \
    } while (0)
void test()
{
    std::vector<func_t> cbs;
    INIT(cbs);
    setNonBlock(0);
    char buffer[1024];
    while (true)
    {
        printf(">>> ");
        fflush(stdout);
        ssize_t s = read(0, buffer, sizeof(buffer) - 1);
        if (s > 0)
        {
            buffer[s - 1] = 0;
            std::cout << "echo# " << buffer << std::endl;
        }
        else if (s == 0)
        {
            std::cout << "read end" << std::endl;
            break;
        }
        else
        {
        }
        EXEC_OTHER(cbs);
        sleep(1);
    }
}
void test1()
{
    std::vector<func_t> cbs;
    INIT(cbs);
    setNonBlock(0);
    char buffer[1024];
    while (true)
    {
        ssize_t s = read(0, buffer, sizeof(buffer) - 1);
        if (s > 0)
        {
            buffer[s - 1] = 0;
            std::cout << "echo# " << buffer << std::endl;
        }
        else if (s == 0)
        {
            std::cout << "read end" << std::endl;
            break;
        }
        else
        {
            // 当我不输入的时候, 底层没有数据, 不算错误, 但是以错误的形式返回了
            // 那怎么区分真的错了, 还是底层没有数据呢? 单纯返回值无法区分
            // std::cout << "result : " << s << " errno : " << strerror(errno) << std::endl;
            // std::cout << "EAGAIN : " << EAGAIN << " EWOULDBLOCK : " << EWOULDBLOCK << std::endl;
            if (errno == EAGAIN || errno == EWOULDBLOCK)
            {
                std::cout << "我没错, 只是没有数据" << std::endl;
                EXEC_OTHER(cbs);
            }
            else if (errno == EINTR)
            {
                continue;
            }
            else
            {
                std::cout << "result : " << s << " errno : " << strerror(errno) << std::endl;
                break;
            }
        }
        sleep(1);
    }
}
int main()
{
    // test();
    test1();
    return 0;
}